## sameDAviewDA
library(here)
library(tidyverse)
library(estimatr)
library(RItools)

load(here("Data", "wrkdat_DA0_new.rda")) ## wrkdat_DA are people who were shown their DA

thecovs <- c(
  "csd_pop_06", "csd_prop_vm_20pct_06", "community_area_km", "vm.norm2"
)

wrkdat_DA1 <- wrkdat_DA0_new %>%
  select(vcid, dauid, vm, social.capital01, community.resp01, one_of(thecovs)) %>%
  filter(!is.na(vm) & !is.na(social.capital01) & !is.na(community.resp01))

table(table(wrkdat_DA1$dauid))
table(wrkdat_DA1$dauid)[table(wrkdat_DA1$dauid) > 1]

thedas <- names(table(wrkdat_DA1$dauid)[table(wrkdat_DA1$dauid) > 1])

sameDAviewDAdat <- wrkdat_DA1 %>%
  dplyr::filter(dauid %in% thedas) %>%
  arrange(dauid)

stopifnot(all(table(sameDAviewDAdat$dauid) > 1))

## How many respondents?
nrow(sameDAviewDAdat)
# [1] 20
## How many DAs
length(unique(sameDAviewDAdat$dauid))
# [1] 10

## No need for vm.norm2. vm alone is fine
sameDAviewDAdat %>%
  arrange(dauid) %>%
  select(vm, vm.norm2, social.capital01, community.resp01)


outcomes <- c(
  "social.capital01", "community.resp01"
)

outpairDiffs <- lapply(split(sameDAviewDAdat[, c(outcomes, "vm")], sameDAviewDAdat$dauid), function(dat) {
  newdat <- dat[order(dat$vm), ]
  as.numeric(newdat[2, ] - newdat[1, ])
})

outpairDiffsDat <- t(simplify2array(outpairDiffs))
colnames(outpairDiffsDat) <- c(outcomes, "vm")
summary(outpairDiffsDat)

outpairDiffsSummary <- apply(outpairDiffsDat, 2, function(x) {
  c(quantile(x, .50 + c(-.375, .375), na.rm = TRUE), mean = mean(x, na.rm = TRUE))
})

res1outvars <- c("social.capital01", "community.resp01")

res1SameDAViewDA <- t(outpairDiffsSummary[, res1outvars])
row.names(res1SameDAViewDA) <- c(
  "Social Cohesion",
  "Collective Efficacy"
)
colnames(res1SameDAViewDA) <- c("lo", "hi", "mean")

sameDAviewDAdat <- sameDAviewDAdat %>%
  group_by(dauid) %>%
  mutate(perc_more = rank(vm) - 1, perc_moreF = factor(perc_more))
sameDAviewDAdat %>%
  arrange(dauid, vm) %>%
  select(dauid, vm, perc_more, social.capital01, community.resp01)

save(sameDAviewDAdat, res1SameDAViewDA, file = here("Analysis", "analysis_sameDAviewDA.rda"))
